<template>
	<div>
		<a-card style="margin-top: 12px;">
			<div>
				<a-form-model layout="horizontal" :model="form" ref="queryForm" :labelCol="{span: 7}"
					:wrapperCol="{span: 17, offset: 0}">
					<div class="fold">
						<a-row>
							<a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
								<a-form-model-item label="用户名" prop="username">
									<a-input v-model="form.username" />
								</a-form-model-item>
							</a-col>
							<a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
								<a-form-model-item label="昵称" prop="nickname">
									<a-input v-model="form.nickname" />
								</a-form-model-item>
							</a-col>
							<a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
								<a-form-model-item label="状态" prop="status">
									<a-select allowClear v-model="form.status"
										:getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}">
										<a-select-option v-for="item in dict.status" :key="item.key"
											:value="item.value">{{item.title}}
										</a-select-option>
									</a-select>
								</a-form-model-item>
							</a-col>
							<a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
								<a-form-model-item label="性别" prop="gender">
									<a-select allowClear v-model="form.gender"
										:getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}">
										<a-select-option v-for="item in dict.gender" :key="item.key"
											:value="item.value">{{item.title}}
										</a-select-option>
									</a-select>
								</a-form-model-item>
							</a-col>
							<a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
								<a-form-model-item label="联系电话" prop="phone">
									<a-input v-model="form.phone" />
								</a-form-model-item>
							</a-col>
							<a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
								<a-form-model-item label="电子邮件" prop="email">
									<a-input v-model="form.email" />
								</a-form-model-item>
							</a-col>
						</a-row>
						<a-row type="flex" justify="end">
							<a-button @click="submitForm" type="primary">查询</a-button>
							<a-button @click="resetForm" style="margin-left: 8px">重置</a-button>
						</a-row>
					</div>
				</a-form-model>
			</div>
		</a-card>
		<a-card style="margin-top: 12px;">
			<a-row>
				<a-col :xxl="4" :lg="4"
					:class="[isFold ? 'animation fold-tree': 'animation', isFold ? '' : 'padding-right-12']">
					<a-spin :spinning="treeLoading">
						<div style="min-height: 600px;overflow-y: auto;overflow-x: hidden;">
							<a-tree :show-icon="true" :show-line="false" :tree-data="organizationTreeData"
								:expandedKeys.sync="expandedKeys" @select="onClickTreeNode">
								<template slot="title" slot-scope="item">
									<span v-if="item.type == 0">
										<a-icon type="bank" /> {{item.customTitle}}
									</span>
									<span v-else-if="item.type == 1">
										<a-icon type="shop" /> {{item.customTitle}}
									</span>
									<span v-else-if="item.type == 2">
										<a-icon type="apartment" /> {{item.customTitle}}
									</span>
									<span v-else>
										<a-icon type="question-circle" /> {{item.customTitle}}
									</span>
								</template>
							</a-tree>
						</div>
					</a-spin>
				</a-col>
				<a-col :xxl="20" :lg="20" :class="isFold ? 'animation fold-table': 'animation'">
					<div>
						<div>
							<a-button class="space-vertical" @click="foldAction">{{isFold ? `展开` : `折叠`}}</a-button>
							<a-button class="space-vertical" @click="showAddModal" type="primary"
								v-auth="`config:user:add`">新增</a-button>
							<a-dropdown>
								<a-button class="space-vertical">批量操作
									<a-icon type="down" />
								</a-button>
								<a-menu @click="batchAction" slot="overlay">
									<a-menu-item key="delete" v-auth="`config:user:delete`">批量删除</a-menu-item>
								</a-menu>
							</a-dropdown>
							<a-button class="space-vertical" @click="exportAction">导出</a-button>
						</div>
						<standard-table ref="table" :size="`middle`" :page="page" :pageSize="pageSize" :total="total"
							:loading="loading" :columns="columns" :dataSource="dataSource"
							:selectedRows.sync="selectedRows" @onPageChange="onPageChange">
							<div slot="action" slot-scope="{text, record}">
								<a @click="resetPasswordAction(record.id)" v-auth="`config:user:resetPassword`">
									重置密码
								</a>
								<a-divider class="row-btn-divider" type="vertical"
									v-auth="`config:user:resetPassword`" />
								<a @click="showQueryModal(record.id)">
									查看
								</a>
								<a-divider class="row-btn-divider" type="vertical" v-auth="`config:user:edit`" />
								<a @click="showEditModal(record.id)" v-auth="`config:user:edit`">
									编辑
								</a>
								<a-divider class="row-btn-divider" type="vertical" v-auth="`config:user:delete`" />
								<a @click="showDeleteModal(record.id)" v-auth="`config:user:delete`">
									删除
								</a>
							</div>
							<div slot="gender" slot-scope="{text}">
								<span>{{text | dictFilter(dict.gender)}}</span>
							</div>
							<div slot="status" slot-scope="{text}">
								<a-badge :status="text == 1 ? 'success' : 'error'"
									:text="text | dictFilter(dict.status)" />
							</div>
						</standard-table>
					</div>
				</a-col>
			</a-row>
			<add-modal ref="addModal" :visible="visibleAddModal" @cancel="hideAddModal" @ok="addSuccess" />
			<edit-modal ref="editModal" :visible="visibleEditModal" @cancel="hideEditModal" @ok="editSuccess" />
			<query-modal ref="queryModal" :visible="visibleQueryModal" @cancel="hideQueryModal" />
		</a-card>
	</div>
</template>

<script>
	import StandardTable from '@/components/table/standard-table'
	import AddModal from './add-modal'
	import EditModal from './edit-modal'
	import QueryModal from './query-modal'
	import {
		userService
	} from '@/services'
	import {
		tableToExcel
	} from '@/utils/excel-util'

	const columns = [{
			title: '序号',
			dataIndex: 'no',
			width: 60,
			scopedSlots: {
				customRender: 'no'
			}
		},
		{
			title: '所属机构',
			dataIndex: 'organizationName',
			width: 150
		},
		{
			title: '用户名',
			dataIndex: 'username',
			width: 120
		},
		{
			title: '昵称',
			dataIndex: 'nickname',
			width: 160
		},
		{
			title: '性别',
			dataIndex: 'gender',
			width: 80,
			scopedSlots: {
				customRender: 'gender'
			}
		},
		{
			title: '联系电话',
			dataIndex: 'phone',
			width: 140
		},
		{
			title: '电子邮件',
			dataIndex: 'email',
			width: 140,
			ellipsis: true
		},
		{
			title: '状态',
			dataIndex: 'status',
			width: 80,
      align: 'center',
			scopedSlots: { customRender: 'status' }
		},
		// {
		//   title: '创建时间',
		//   dataIndex: 'createTime',
		//   width: 150
		// },
		// {
		//   title: '更新时间',
		//   dataIndex: 'updateTime',
		//   width: 150
		// },
		{
			title: '操作',
			width: 220,
			align: 'center',
			scopedSlots: { customRender: 'action' }
		}
	]

	export default {
		name: 'User',
		components: {
			StandardTable,
			AddModal,
			EditModal,
			QueryModal
		},
		data() {
			return {
				isFold: false,
				loading: false,
				confirmLoading: false,
				treeLoading: false,
				page: 1,
				pageSize: 10,
				total: 0,
				columns: columns,
				dataSource: [],
				selectedRows: [],
				form: {
					username: undefined,
					nickname: undefined,
					gender: undefined,
					phone: undefined,
					email: undefined,
					status: undefined,
					organizationId: undefined
				},
				dict: {
					gender: [],
					status: []
				},
				visibleAddModal: false,
				visibleEditModal: false,
				visibleQueryModal: false,
				organizationTreeData: [],
				expandedKeys: []
			}
		},
		filters: {
			dictFilter: (val, dictList) => {
				const dict = dictList.find(item => item.value == val)
				return dict ? dict.title : '未知'
			}
		},
		authorize: {
			showQueryModal: 'config:user:query',
			showAddModal: 'config:user:add',
			showEditModal: 'config:user:edit',
			deleteAction: 'config:user:delete',
			showBatchDeleteModal: 'config:user:delete',
			resetPasswordAction: 'config:user:resetPassword',
			// showImportModal: 'config:user:import',
			// exportAction: 'config:user:export'
		},
		methods: {
			foldAction() {
				this.isFold = !this.isFold
			},
			reloadTable() {
				this.selectedRows = []
				this.page = 1
				this.queryListAction()
			},
			resetForm() {
				this.$refs.queryForm.resetFields()
				this.reloadTable()
			},
			submitForm() {
				this.reloadTable()
			},
			showImportModal() {
				this.$message.success('敬请期待!')
			},
			exportAction() {
				// this.$message.success('敬请期待!')
				let columns = this.$refs.table.columns;
				let widths = []
				for(var i=0; i<columns.length; i++){
					widths.push({wpx: columns[i].width})
				}
				tableToExcel(document.querySelector('table'), widths, '用户管理')
			},
			showAddModal() {
				this.visibleAddModal = true
				this.$refs.addModal.queryOrganizationTreeAction(this.form.organizationId)
				this.$refs.addModal.queryRoleSelectAction(this.form.organizationId)
			},
			showEditModal(key) {
				this.visibleEditModal = true
				this.$refs.editModal.queryOrganizationTreeAction(this.form.organizationId)
				this.$refs.editModal.queryRoleSelectAction(this.form.organizationId)
				this.$refs.editModal.queryAction(key)
			},
			showQueryModal(key) {
				this.visibleQueryModal = true
				this.$refs.queryModal.queryOrganizationTreeAction(this.form.organizationId)
				this.$refs.queryModal.queryRoleSelectAction(this.form.organizationId)
				this.$refs.queryModal.queryAction(key)
			},
			hideAddModal() {
				this.visibleAddModal = false
				this.$refs.addModal.$refs.form.resetFields()
			},
			hideEditModal() {
				this.visibleEditModal = false
				this.$refs.editModal.$refs.form.resetFields()
			},
			hideQueryModal() {
				this.visibleQueryModal = false
			},
			addSuccess() {
				this.hideAddModal()
				this.reloadTable()
			},
			editSuccess() {
				this.hideEditModal()
				this.reloadTable()
			},
			deleteAction(keys) {
				this.confirmLoading = true
				const params = {
					ids: keys
				}
				return userService.del(JSON.stringify(params)).then(res => {
					const result = res.data
					if (result.code === 200) {
						this.$message.success(result.msg)
						this.selectedRows = []
						this.reloadTable()
					}
				}).finally(this.confirmLoading = false)
			},
			batchAction(e) {
				if (this.selectedRows.length <= 0) {
					this.$message.warning('请选择记录后操作')
					return
				}
				if (e.key === 'delete') {
					this.showBatchDeleteModal()
				}
			},
			showDeleteModal(key) {
				this.$confirm({
					confirmLoading: this.confirmLoading,
					icon: 'info-circle',
					title: '警告',
					content: '你确定要删除此项吗？',
					okType: 'danger',
					onOk: () => {
						this.deleteAction([key])
					},
					onCancel() {},
				})
			},
			showBatchDeleteModal() {
				this.$confirm({
					confirmLoading: this.confirmLoading,
					icon: 'info-circle',
					title: '警告',
					content: '你确定要删除所有选中项吗？',
					okType: 'danger',
					onOk: () => {
						this.deleteAction(this.selectedRows.map(item => item.id))
					},
					onCancel() {},
				})
			},
			resetPasswordAction(key) {
				this.loading = true
				const params = {
					id: key
				}
				userService.resetPassword(JSON.stringify(params)).then(res => {
					const result = res.data
					if (result.code === 200) {
						this.$message.success(result.msg)
					}
				}).finally(this.loading = false)
			},
			onPageChange(pagination) {
				this.page = pagination.current
				this.pageSize = pagination.pageSize
				this.queryListAction()
			},
			onClickTreeNode(selectedKeys) {
				this.form.organizationId = selectedKeys[0]
				this.reloadTable()
			},
			queryListAction() {
				this.loading = true
				const params = {
					page: this.page,
					pageSize: this.pageSize,
					queryParams: this.form
				}
				userService.queryList(JSON.stringify(params)).then(res => {
					const result = res.data
					if (result.code === 200) {
						this.dataSource = []
						this.dataSource = result.data.records
						this.total = result.data.totalCount
					}
				}).finally(this.loading = false)
			},
			queryOrganizationAction() {
				this.treeLoading = true
				userService.queryOrganizationTree().then(res => {
					const result = res.data
					if (result.code === 200) {
						this.organizationTreeData = result.data
						this.expandedKeys = []
						this.expandAllTreeNode(this.organizationTreeData, this.expandedKeys)
					}
				}).finally(this.treeLoading = false)
			},
			expandAllTreeNode(originData, targetData) {
				originData.forEach(item => {
					targetData.push(item.key)
					if (item.children && item.children.length > 0) {
						this.expandAllTreeNode(item.children, targetData)
					}
				})
			}
		},
		created() {
			this.getDict(JSON.stringify({
				code: 'SYS_GENDER'
			})).then(res => this.dict.gender = res.data.data)
			this.getDict(JSON.stringify({
				code: 'SYS_STATUS'
			})).then(res => this.dict.status = res.data.data)
			this.queryOrganizationAction()
			this.reloadTable()
		}
	}
</script>
<style scoped lang="less">
	.ant-form-item {
		margin-bottom: 12px;
	}

	.fold {
		width: calc(100% - 12px);
		display: inline-block;
	}

	@media screen and (max-width: 900px) {
		.fold {
			width: 100%;
		}
	}

	.animation {
		transition: 0.5s;
		-webkit-transition: 0.5s;
	}

	.fold-tree {
		width: 0%;
	}

	.fold-table {
		width: 100%;
	}
</style>
